package com.linx.commonlib.util


import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.util.Log
import com.linx.commonlib.BuildConfig

class Utils private constructor() {

    init {
        throw UnsupportedOperationException("u can't instantiate me...")
    }

    companion object {

        var DEBUG = BuildConfig.DEBUG

        @SuppressLint("StaticFieldLeak")
        private lateinit var sApplication: Application

        /**
         * Init utils.
         *
         * Init it in the class of Application.
         *
         * @param context context
         */
        fun init(context: Context) {
            init(context.applicationContext as Application)
        }

        /**
         * Init utils.
         *
         * Init it in the class of Application.
         *
         * @param app application
         */
        fun init(app: Application) {
            Utils.sApplication = app
        }

        /**
         * Return the context of Application object.
         *
         * @return the context of Application object
         */
        val app: Application
            get() {
                if (sApplication != null) return sApplication
                throw NullPointerException("u should init first")
            }

        internal val isAppForeground: Boolean
            get() {
                val am = Utils.app.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
                        ?: return false
                val info = am.runningAppProcesses
                if (info == null || info.size == 0) return false
                for (aInfo in info) {
                    if (aInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        return aInfo.processName == Utils.app.packageName
                    }
                }
                return false
            }

        fun log(priority: Int, tag: String, format: String, vararg args: Any) {
            if (DEBUG) {
                val msg = String.format(format, *args)
                try {
                    Log.println(priority, tag, msg)
                } catch (e: Exception) {
                    println("$tag: $msg")
                }

            }
        }
    }

}

